#!/bin/sh

# 设置文件夹路径
if [ -z "$1" ]; then
    echo "请输入设置文件夹路径"
    exit 1
fi
folder=$1

# 获取文件夹内所有文件的列表，并按修改时间排序
files=$(ls -t "$folder" | grep -v '/$')

# 获取文件总数
total_files=$(echo "$files" | wc -l)

# 计算需要保留的文件数量
if [ -z "$2" ]; then
    echo "请输入保留的文件数量"
    exit 1
fi
keep_files=$2

# 计算需要删除的文件数量
delete_files=$((total_files - keep_files))

# 如果需要删除的文件数量大于 0，则删除多余的文件
if [ "$delete_files" -gt 0 ]; then
    echo "Total files: $total_files"
    echo "Keeping $keep_files files, deleting $delete_files files"

    # 删除多余的文件
    for file in $(echo "$files" | tail -n +$(($keep_files + 1))); do
        echo "Deleting $file"
        rm "$folder/$file"
    done
else
    echo "No files to delete. Total files: $total_files"
fi
